<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <title>蜗牛车辆预约</title>
        <meta name="description" content="蜗牛车辆预约">
        <meta name="keywords" content="蜗牛车辆预约">
        <meta content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no" name="viewport">
        <link rel="stylesheet" href="../plugins/elementui/index.css">
        <link rel="stylesheet" href="../plugins/font-awesome/css/font-awesome.min.css">
        <link rel="stylesheet" href="../css/style.css">
        <style>
            .avatar-uploader .el-upload {
                border: 1px dashed #d9d9d9;
                border-radius: 6px;
                cursor: pointer;
                position: relative;
                overflow: hidden;
            }
            .avatar-uploader .el-upload:hover {
                border-color: #409EFF;
            }
            .avatar-uploader-icon {
                font-size: 28px;
                color: #8c939d;
                width: 178px;
                height: 178px;
                line-height: 178px;
                text-align: center;
            }
            .avatar {
                width: 178px;
                height: 178px;
                display: block;
            }
        </style>
    </head>
    <body class="hold-transition">
        <div id="app">
            <div class="content-header">
                <h1>车辆管理<small>车辆列表</small></h1>
                <el-breadcrumb separator-class="el-icon-arrow-right" class="breadcrumb">
                    <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
                    <el-breadcrumb-item>车辆管理</el-breadcrumb-item>
                </el-breadcrumb>
            </div>
            <div class="app-container">
                <div class="box">
                     <div class="filter-container">
                        <el-input v-model="carSearchDTO.title" placeholder="车辆名称" style="width: 200px;" class="filter-item"></el-input>
                         <el-select v-model="carSearchDTO.energy">
                             <el-option label="汽油" value="1"></el-option>
                             <el-option label="新能源" value="2"></el-option>
                             <el-option label="混合动力" value="3"></el-option>
                         </el-select>
                         <el-date-picker
                                 v-model="createTimeDatePicker"
                                 type="daterange"
                                 range-separator="至"
                                 start-placeholder="开始日期"
                                 end-placeholder="结束日期">
                         </el-date-picker>
                        <el-button class="dalfBut" @click="handleSearch">查询</el-button>
                        <el-button class="dalfBut" @click="handleSearchClear">清空</el-button>
                        <el-button type="primary" class="butT" @click="handleToAdd">新增</el-button>
                        <el-button type="primary" class="butT" @click="handleDeleteBatch(undefined)">批量删除</el-button>
                    </div>
                    <el-table size="small" current-row-key="id" :data="dataList" @selection-change="handleSelectionChange" stripe highlight-current-row>
                        <el-table-column type="selection" width="55">
                        </el-table-column>
                        <el-table-column type="index" align="center" label="序号"></el-table-column>
                        <el-table-column prop="title" label="车辆名称" align="center"></el-table-column>
                        <el-table-column prop="energy" label="能源类型" align="center">
                            <template slot-scope="scope">
                                <span v-if="scope.row.energy == 1">汽油</span>
                                <span v-if="scope.row.energy == 2">新能源</span>
                                <span v-if="scope.row.energy == 3">混合动力</span>
                            </template>
                        </el-table-column>
                        <el-table-column prop="imgUrl" label="车辆图片" align="center">
                            <template slot-scope="scope">
                                <img :src="scope.row.imgUrl" style="height: 70px;" />
                            </template>
                        </el-table-column>
                        <el-table-column prop="price" label="日租价格" align="center"></el-table-column>
                        <el-table-column prop="createTime" label="创建时间" align="center"></el-table-column>
                        <el-table-column prop="isShow" label="是否显示" align="center">
                            <template slot-scope="scope">
                                <el-switch
                                        style="display: block"
                                        v-model="scope.row.isShow"
                                        active-color="#13ce66"
                                        inactive-color="#ff4949"
                                        active-text="显示"
                                        inactive-text="隐藏"
                                        active-value="1"
                                        inactive-value="0"
                                        @change="handleIsShowChange($event, scope.row.id)">
                                </el-switch>
                            </template>
                        </el-table-column>
                        <el-table-column label="操作" align="center">
                            <template slot-scope="scope">
                                <el-button type="primary" size="mini" @click="handleToEdit(scope.row.id)">编辑</el-button>
                                <el-button size="mini" type="danger" @click="handleDeleteBatch(scope.row.id)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>

                    <el-pagination
                            @size-change="handleSizeChange"
                            @current-change="handleCurrentChange"
                            :current-page="carSearchDTO.currentPage"
                            :page-sizes="[10, 20, 30, 50]"
                            :page-size="carSearchDTO.pageSize"
                            layout="total, sizes, prev, pager, next, jumper"
                            :total="total">
                    </el-pagination>

                    <!-- 新增标签弹层 -->
                    <div class="add-form">
                        <el-dialog :title="dialogTitle" :visible.sync="addDialogFormVisible" @close="resetForm" :close-on-click-modal="false">
                            <el-form label-position="right" label-width="100px" :model="car" :rules="rules" ref="carForm">
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="车辆名称" prop="title">
                                            <el-input v-model="car.title" placeholder="请输入车辆名称"/>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="车辆类型" prop="typeId">
                                            <el-select v-model="car.typeId">
                                                <el-option v-for="carType in carTypeList" :label="carType.name" :value="carType.id"></el-option>
                                            </el-select>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="车辆库存" prop="stock">
                                            <el-input v-model="car.stock" placeholder="请输入车辆库存"/>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="门店" prop="shopId">
                                            <el-select v-model="car.shopId">
                                                <el-option v-for="shop in shopList" :label="shop.name" :value="shop.id"></el-option>
                                            </el-select>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="能源类型">
                                            <el-select v-model="car.energy">
                                                <el-option label="汽油" value="1"></el-option>
                                                <el-option label="新能源" value="2"></el-option>
                                                <el-option label="混合动力" value="3"></el-option>
                                            </el-select>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="品牌" prop="brandId">
                                            <el-select v-model="car.brandId" clearable>
                                                <el-option v-for="brand in brandList" :label="brand.name" :value="brand.id"></el-option>
                                            </el-select>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="变速箱">
                                            <el-input v-model="car.speedBox" placeholder="请输入变速箱类型"/>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="车辆动力">
                                            <el-input v-model="car.power" placeholder="请输入车辆动力"/>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="车辆座位">
                                            <el-input v-model="car.seat" placeholder="请输入车辆座位"/>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="油箱容量">
                                            <el-input v-model="car.tank" placeholder="请输入油箱容量"/>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="日租价格">
                                            <el-input v-model="car.price" placeholder="请输入日租价格"/>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="车辆特点">
                                            <el-input v-model="car.feature" placeholder="请输入车辆特点"/>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="8">
                                        <el-form-item label="显示">
                                            <template>
                                                <el-radio v-model="car.isShow" label="0">否</el-radio>
                                                <el-radio v-model="car.isShow" label="1">是</el-radio>
                                            </template>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="8">
                                        <el-form-item label="新车">
                                            <template>
                                                <el-radio v-model="car.isNew" label="0">否</el-radio>
                                                <el-radio v-model="car.isNew" label="1">是</el-radio>
                                            </template>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="8">
                                        <el-form-item label="热租">
                                            <template>
                                                <el-radio v-model="car.isHot" label="0">否</el-radio>
                                                <el-radio v-model="car.isHot" label="1">是</el-radio>
                                            </template>
                                        </el-form-item>
                                    </el-col>
                                </el-row>

                                <el-row>
                                    <el-col :span="24">
                                        <el-form-item label="车辆图片封面">
                                            <el-upload
                                                    class="avatar-uploader"
                                                    action="http://43.136.35.8:8090/common/upload/"
                                                    :show-file-list="false"
                                                    :on-success="handleAvatarSuccess"
                                                    :before-upload="beforeAvatarUpload">
                                                <!--用于图片回显-->
                                                <img v-if="car.imgUrl" :src="car.imgUrl" class="avatar">
                                                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                                            </el-upload>
                                        </el-form-item>
                                    </el-col>
                                </el-row>

                                <el-row>
                                    <el-col :span="24">
                                        <el-form-item label="车辆图片列表">
                                            <el-upload
                                                    class="avatar-uploader"
                                                    action="http://43.136.35.8:8090/common/upload/"
                                                    list-type="picture-card"
                                                    :limit="3"
                                                    :file-list="carImgList"
                                                    :on-success="handleAvatarSuccessPro"
                                                    :before-upload="beforeAvatarUpload"
                                                    :on-remove="handleRemove"
                                                    :on-exceed="handleExceed">
                                                <!--用于图片回显-->
                                                <i class="el-icon-plus"></i>
                                            </el-upload>
                                        </el-form-item>
                                    </el-col>
                                </el-row>

                            </el-form>
                            <div slot="footer" class="dialog-footer">
                                <el-button @click="addDialogFormVisible = false">取消</el-button>
                                <el-button type="primary" @click="handleAddOrUpdate">确定</el-button>
                            </div>
                        </el-dialog>
                    </div>
                </div>
            </div>
        </div>
    </body>
    <!-- 引入组件库 -->
    <script src="../js/vue.js"></script>
    <script src="../plugins/elementui/index.js"></script>
    <script type="text/javascript" src="../js/jquery.min.js"></script>
    <script src="../js/axios-0.18.0.js"></script>
    <script>

        const checkTitleExist = (rule, value, callback) => {
            axios.get("/car/check/title/" + value).then(res => {
                if(!res.data.data){
                    callback();
                }else{
                    // 把自己排除掉
                    if(res.data.data.id == vue.car.id){
                        callback();
                    }else{
                        callback(new Error("该标题已经被使用"));
                    }
                }
            });
        }

        let vue = new Vue({
            el: '#app',
            data:{
				dataList: [],                       // 分页数据
                car: {imgUrl: '', carImgList: []},  // 表单数据
                addDialogFormVisible: false,        // 新增表单是否可见
                createTimeDatePicker: '',           // 时间区间选择
                carSearchDTO:{                      // 表示搜索的内容
				    title: '',
                    energy: '',
                    createTimeStart: '',
                    createTimeEnd: '',
                    currentPage: 1,
                    pageSize: 10
                },
                total: 10,                          // 总记录数
                ids: [],                            // 多选列表
                dialogTitle: '',                    // 弹框名称
                carImgList: [],                     // 图片列表
                shopList: [],                       // 门店列表
                brandList: [],                      // 品牌列表
                carTypeList: [],                    // 车辆类型列表
                rules: {                            // 校验规则
                    title:[
                        { required: true, message: '请输入车辆名称', trigger: 'blur' },
                        { min: 3, max: 8, message: '长度在 3 到 8 个字符', trigger: 'blur' },
                        { required: true, validator: checkTitleExist, trigger: 'blur' }
                    ],
                    shopId:[
                        { required: true, message: '请选择门店', trigger: 'change' },
                    ],
                    typeId:[
                        { required: true, message: '请选择类型', trigger: 'change' },
                    ],
                    brandId:[
                        { required: true, message: '请选择品牌', trigger: 'change' },
                    ],
                    stock:[
                        { required: true, message: '请填写库存', trigger: 'blur' },
                    ]
                },

            },
            methods: {
                // 初始化查询数据，查询按钮
                handleSearch(){
                    // 1. 将用户选择的时间区间 保存到 carSearchDTO里面
                    if(this.createTimeDatePicker){
                        this.carSearchDTO.createTimeStart = this.createTimeDatePicker[0];
                        this.carSearchDTO.createTimeEnd = this.createTimeDatePicker[1];
                    }
                    // 发送请求查询数据
                    axios.post("/car/search", this.carSearchDTO).then(res => {
                        this.dataList = res.data.data.data;
                        this.total = res.data.data.total;
                    });
                },
                // 清空搜索内容
                handleSearchClear(){
                    this.carSearchDTO.title = '';
                    this.carSearchDTO.energy = '';
                    this.carSearchDTO.createTimeStart = '';
                    this.carSearchDTO.createTimeEnd = '';
                },
                // 每页记录数发生变化触发
                handleSizeChange(pageSize){
                    // 更改数据模型中的每页记录数
                    this.carSearchDTO.pageSize = pageSize;
                    // 重新查询数据
                    this.handleSearch();
                },
                // 页码发生变化触发
                handleCurrentChange(currentPage){
                    // 更改数据模型中的当前页
                    this.carSearchDTO.currentPage = currentPage;
                    // 重新查询数据
                    this.handleSearch();
                },
                // 是否显示开关切换事件
                handleIsShowChange(isShowValue, id){
                    axios.put(`/car/show/${id}/${isShowValue}`).then(res => {
                        if(res.data.code == 20000){
                            this.$message.success("更新显示状态成功");
                        }else{
                            this.$message.errow("更新显示状态失败，请稍候再试");
                        }
                    });
                },
                // 显示新增窗口
                async handleToAdd(){
                    await this.resetForm();
                    this.addDialogFormVisible = true;
                    this.dialogTitle = '新增';
                    // 获取门店信息
                    this.listAllShop();
                    // 获取品牌信息
                    this.listAllBrand();
                    // 获取车辆类型信息
                    this.listAllCarType();
                },
                // 重置表单数据
                resetForm(){
                    this.carImgList = [];
                    this.car = {imgUrl: '', carImgList: []};
                    if(this.$refs['carForm'] != undefined){
                        this.$refs['carForm'].resetFields();
                    }
                },
                // 图片上传成功之后回调该函数
                handleAvatarSuccess(res, file) {
                    // 此时的res就是表示result对象（注意不要搞错了）
                    this.car.imgUrl = res.data;
                },
                // 图片列表上传
                handleAvatarSuccessPro(res, file){
                    this.carImgList.push({name: file.name, url: res.data});
                    console.log(this.carImgList);
                },
                handleExceed(files, carImgList) {
                    this.$message.warning(`当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + carImgList.length} 个文件`);
                },
                // 删除图片
                handleRemove(file, carImgList){
                    console.log(file.name, carImgList);
                    this.carImgList.pop({name: file.name, url: file.url});
                },
                // 图片上传之前执行
                beforeAvatarUpload(file) {
                    const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
                    const isLt10M = file.size / 1024 / 1024 < 10;
                    if (!isJPG) {
                        this.$message.error('上传头像图片只能是 JPG 格式!');
                    }
                    if (!isLt10M) {
                        this.$message.error('上传头像图片大小不能超过 10MB!');
                    }
                    return isJPG && isLt10M;
                },
                // 新增或者修改操作
                handleAddOrUpdate(){
                    console.log("车辆封面：" + this.car.imgUrl);
                    console.log("车辆图片列表：" + this.carImgList);
                    // 将图片中url提取出来
                    this.car.carImgList = this.carImgList.map(item => item.url);
                    console.log("车辆图片列表(发送给后端的)：" + this.car.carImgList);

                    this.$refs['carForm'].validate((valid) => {
                        if(valid){
                            if(this.car.id){// 编辑操作
                                axios.put("/car", this.car).then(res => {
                                    if(res.data.code == 20000){
                                        this.$message.success("修改成功");
                                        this.addDialogFormVisible = false;
                                        this.handleSearch();
                                    }else{
                                        this.$message.error("修改失败，请稍后再试");
                                    }
                                });
                            }else{// 新增操作
                                axios.post("/car", this.car).then(res => {
                                    if(res.data.code == 20000){
                                        this.$message.success("保存成功");
                                        this.addDialogFormVisible = false;
                                        this.handleSearch();
                                    }else{
                                        this.$message.error(res.data.message);
                                    }
                                });
                            }
                        }else{
                            this.$message.error("请正确填写数据");
                        }
                    });
                },
                // 打开编辑窗口
                handleToEdit(id){
                    this.resetForm();
                    axios.get("/car/" + id).then(res => {
                        this.car = res.data.data;
                        this.addDialogFormVisible = true;
                        this.dialogTitle = '修改';
                        console.log(res.data.data)
                        res.data.data.carImgList.forEach(item => {
                            this.carImgList.push({name: item, url: item})
                        })
                        // 获取门店信息
                        this.listAllShop();
                        // 获取品牌信息
                        this.listAllBrand();
                        // 获取车辆类型信息
                        this.listAllCarType();
                    });
                },
                // 多选事件
                handleSelectionChange(selection){
                    this.ids = selection.map(item => item.id)
                },
                // 批量删除
                handleDeleteBatch(id){
                    if(id){
                        this.ids = id;
                    }
                    if(this.ids == undefined || this.ids.length == 0){
                        this.$message.info("请选择需要删除的数据");
                        return;
                    }
                    this.$confirm('是否确认删除编号为"' + this.ids + '"的数据项？').then(() => {
                        axios.delete("/car/" + this.ids).then(res => {
                            if(res.data.code == 20000){
                                this.$message.success("删除成功");
                                this.handleSearch();
                            }else{
                                this.$message.error("删除失败，请稍后再试");
                            }
                        });
                    }).catch(() => {
                        this.$message.info("取消删除操作");
                    });
                },
                // 获取所有门店信息
                listAllShop(){
                    axios.get("/shop").then(res => {
                        this.shopList = res.data.data;
                    });
                },
                // 获取所有品牌信息
                listAllBrand(){
                    axios.get("/brand").then(res => {
                        this.brandList = res.data.data;
                    });
                },
                // 获取所有品牌信息
                listAllCarType(){
                    axios.get("/carType").then(res => {
                        this.carTypeList = res.data.data;
                    });
                }
            },
            created(){
                this.handleSearch();
            }
        })
    </script>
</html>
